// pages/welfare/welfare.js
var WXBizDataCrypt = require('../../utils/cryptojs/RdWXBizDataCrypt.js');
var util = require('../../utils/util.js')
//获取应用实例
var app = getApp();
var key = app.globalData.key;
const resurl = app.globalData.resurl;
var deviceProperties = app.globalData.deviceProperties;
let interstitialAd = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isDelay: '',
    videoMoney: "",
    isReview: '',
    isReview1: '',
    gameShow: true,
    showMaskNext: false,
    timeShow: false,
    showBtn: false,
    money: '',
    userMoney: '',
    fourShow: false,
    showMask: false,
    showTomrorrow: false,
    showLastDay: false,
    signDay: '',
    isSign: '',
    jobsList: [],
    statusList: ['去完成', '领取', '明天再来'],
    bindWxStatus: ['去完成', '领取', '已完成'],
    statusColor: ['linear-gradient(0deg,rgba(248,61,49,1),rgba(255,94,84,1))',
      'linear-gradient(0deg,rgba(252,151,98,1),rgba(254,173,99,1))',
      'linear-gradient(0deg,rgba(90,192,246,1),rgba(21,168,253,1))',
    ],
    arrList: [

      {
        days: '1天',
        signingSrc: '/images/image_gold.png',
        signedSrc: '/images/image_gold_signedDay.png',
        signingColor: 'rgba(51,51,51,1)',
        signedColor: 'rgba(255,176,13,1)',
      },
      {
        days: '2天',
        signingSrc: '/images/image_gold.png',
        signedSrc: '/images/image_gold_signedDay.png',
        signingColor: 'rgba(51,51,51,1)',
        signedColor: 'rgba(255,176,13,1)',
      },
      {
        days: '3天',
        signingSrc: '/images/image_gold.png',
        signedSrc: '/images/image_gold_signedDay.png',
        signingColor: 'rgba(51,51,51,1)',
        signedColor: 'rgba(255,176,13,1)',
      },
      {
        days: '4天',
        signingSrc: '/images/image_gold.png',
        signedSrc: '/images/image_gold_signedDay.png',
        signingColor: 'rgba(51,51,51,1)',
        signedColor: 'rgba(255,176,13,1)',
      },
      {
        days: '5天',
        signingSrc: '/images/image_gold.png',
        signedSrc: '/images/image_gold_signedDay.png',
        signingColor: 'rgba(51,51,51,1)',
        signedColor: 'rgba(255,176,13,1)',
      },
      {
        days: '6天',
        signingSrc: '/images/image_gold.png',
        signedSrc: '/images/image_gold_signedDay.png',
        signingColor: 'rgba(51,51,51,1)',
        signedColor: 'rgba(255,176,13,1)',
      },
      {
        days: '7天',
        signingSrc: '/images/image_gold.png',
        signedSrc: '/images/image_gold_signedDay.png',
        signingColor: 'rgba(51,51,51,1)',
        signedColor: 'rgba(255,176,13,1)',
      },
    ],
  },
  insertScreenAdTimer: '',
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    if (options.unionId !== undefined) {
      that.setData({
        parentUnionId: options.unionId
      })
    }

    var videoMoney = wx.getStorageSync("videoMoney")
    var isDelay = wx.getStorageSync("isDelay");
    that.setData({
      videoMoney,
      isDelay,
    })
  },
  // 当点击已领取时，弹出弹窗明天再来
  toastOut: function () {
    var that = this;
    that.setData({
      showTomrorrow: true,
      showLastDay: true,
    })
    // that.insertScreenAD();
  },
   // 关闭game广告
   closeGame: function () {
    this.setData({
      gameShow: false,
    })
  },
  insertScreenAD: function () {
    // 在页面onLoad回调事件中创建插屏广告实例
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: 'adunit-1cc4cb154d00aa08'
      })
      interstitialAd.onLoad(() => { })
      interstitialAd.onError((err) => { })
      interstitialAd.onClose(() => { })
    }

    // 在适合的场景显示插屏广告
    if (interstitialAd) {
      interstitialAd.show().catch((err) => {
        console.error(err)
      })
    }
  },
  // 关闭弹窗
  close: function () {
    var that = this;
    var isDelay = that.data.isDelay;
    if(isDelay == 1) {
      var delayTimer = setInterval(function () {
        that.setData({
          showTomrorrow: false,
          showLastDay: false,
        })
        clearInterval(delayTimer);
      },2000)
    } else {
      that.setData({
        showTomrorrow: false,
        showLastDay: false,
      })
    }
  },
  // 关闭领取奖励的弹窗
  clickcloseReward: function () {
    this.setData({
      timeShow: false,
      showMaskNext: false,
    })
  },
  //领取福利接口 9
  getMoneyInterface: function (jobId, index) {
    var that = this;
    var money = that.data.money;
    var jobsList = that.data.jobsList;
    var userId = wx.getStorageSync("userId");
    var data9 = {
      deviceProperties: app.globalData.deviceProperties,
      user: {
        userId: userId,
        jobId: jobId,
      }
    }
    data9 = JSON.stringify(data9);
    data9 = util.base64_encode(data9);
    data9 = util.xxtea_encrypt(data9, key);
    wx.request({
      url: resurl + '/interface/sdkData?requestId=9&a=1&b=2',
      data: data9,
      header: {
        "content-type": "application/json",
        "dataType": "json",
      },
      method: "post",
      success: function (res) {
        res = util.xxtea_decrypt(res.data, key);
        res = util.base64_decode(res);
        res = JSON.parse(res);
        console.log(res);
        if (res.resultCode === 0) {
          res = JSON.parse(res.data);
          var app = getApp();
          app.globalData.money = money + res.getMoney;
          that.setData({
            // jobsList: jobsList,
            money: app.globalData.money,
          })
          that.timeToast(res.getMoney);
          that.onShow();
        }

      }
    })
  },
  //header部分点击提现
  getmoney: function (e) {
    wx.navigateTo({
      url: '/pages/getMoney/getMoney'
    })
  },
  // 绑定微信
  clockLogin: function (e) {
    var that = this;
    var jobsList = e.currentTarget.dataset.jobslist;
    var index = 0;
    if (jobsList[0].isEnd === 0) {
      // 用户授权
      // that.bindGetUserInfo();
      that.getWelfareInfo();
    } else if (jobsList[0].isEnd === 1) {
      that.getMoneyInterface(jobsList[0].id, index);
      that.getWelfareInfo();
    } else if (jobsList[0].isEnd === 2) {
      // that.toastOut();
      wx.showModal({
        title: '已绑定微信',
        shwoCancel: false,
        // content: '请稍后再试！',
      })
    }
  },
  // 用户授权
  bindGetUserInfo: function () {
    var that = this;
    // var userId = wx.getStorageSync("userId");
    wx.login({
      success: function (ress) {
        // console.log(ress)
        wx.getUserInfo({
          success: function (res) {
            // console.log(res);
            var jsonStr = {
              code: ress.code,
              appId: 'wxa8472e39b0ca16a7',
              iv: res.iv,
              encryptedData: res.encryptedData
            };
            deviceProperties.jsonStr = jsonStr;
            // console.log(deviceProperties);
            var data2 = {
              deviceProperties: deviceProperties,
            }
            data2 = JSON.stringify(data2);
            data2 = util.base64_encode(data2);
            data2 = util.xxtea_encrypt(data2, key);
            wx.request({
              url: resurl + '/interface/sdkData?requestId=2&a=1&b=2',
              data: data2,
              header: {
                'Content-Type': 'application/json',
                'dataType': 'json'
              },
              method: "POST",
              success: function (res) {
                res = util.xxtea_decrypt(res.data, key);
                res = util.base64_decode(res);
                res = JSON.parse(res);
                console.log(res);
                if (res.resultCode == 0) {
                  res = JSON.parse(res.data);
                  console.log(res)
                  // wx.hideLoading();
                }
              }
            })
          }
        })
      }
    })
  },


  // 第一笔提现
  turnTixian: function () {
    wx.navigateTo({
      url: '/pages/getMoney/getMoney'
    })
  },
  GetMoney: function (e) {
    var that = this;
    var index = 1;
    var jobsList = e.currentTarget.dataset.jobslist;
    if (jobsList[1].isEnd === 0) {
      wx.navigateTo({
        url: '/pages/getMoney/getMoney'
      })
    } else if (jobsList[1].isEnd === 1) {
      that.getMoneyInterface(jobsList[1].id, index);
      that.getWelfareInfo();
    }
    else if (jobsList[1].isEnd === 2) {
      that.toastOut();
    }
  },
  // 看视频搞钱
  toLookVideo: function () {
    wx.switchTab({
      url: '/pages/calendar/calendar',
      success: (result) => {
        // console.log(success)
      },
      fail: () => { },
      complete: () => { }
    })
  },
  watchVideo: function (e) {
    var that = this;
    var index = 2;
    var jobsList = e.currentTarget.dataset.jobslist;
    if (jobsList[2].isEnd === 0) {
      // 去完成看视频这个任务
      wx.switchTab({
        url: '/pages/calendar/calendar',
        success: (result) => {
          // console.log(success)
        },
        fail: () => { },
        complete: () => { }
      })
    } else if (jobsList[2].isEnd === 1) {
      that.getMoneyInterface(jobsList[2].id, index);
      that.getWelfareInfo();
    }
    else if (jobsList[2].isEnd === 2) {
      that.toastOut();
    }
  },
  //查看日历
  watchClander: function () {
    wx.switchTab({
      url: '/pages/day/day',
      success: (result) => {
        // console.log(success)
      },
      fail: () => { },
      complete: () => { }
    })
  },
  //查看日历 领取金币
  start: function (e) {
    var that = this;
    var jobsList = e.currentTarget.dataset.jobslist;
    var index = 3;
    if (jobsList[3].isEnd === 0) {
      wx.switchTab({
        url: '/pages/day/day',
        success: (result) => {
          // console.log(success)
        },
        fail: () => { },
        complete: () => { }
      })
    } else if (jobsList[3].isEnd === 1) {
      that.getMoneyInterface(jobsList[3].id, index);
      that.getWelfareInfo();
    } else if (jobsList[3].isEnd === 2) {
      that.toastOut();
    }
  },
  //跳转到首页开悬浮窗
  turnCalendar: function () {
    wx.switchTab({
      url: '/pages/calendar/calendar',
      success: (result) => {
        // console.log(success)
      },
      fail: () => { },
      complete: () => { }
    })
  },
  //打开悬浮窗
  openFloatingWindow: function (e) {
    var that = this;
    var index = 4;
    var jobsList = e.currentTarget.dataset.jobslist;
    if (jobsList[4].isEnd === 0) {
      wx.switchTab({
        url: '/pages/calendar/calendar',
        success: (result) => {
        },
        fail: () => { },
        complete: () => { }
      })
    }
    else if (jobsList[4].isEnd === 1) {
      that.getMoneyInterface(jobsList[4].id, index);
      that.getWelfareInfo();
    } else if (jobsList[4].isEnd === 2) {
      that.toastOut();
    }
  },
  //跳转早睡打卡界面：
  morningAndSleep: function () {
    let now = new Date();
    let timeStamp = now.getTime();
    let beginTime = function (begintime) {
      var bArray = begintime.split(":");
      if (bArray.length !== 2) {
        return false;
      }
      var b = new Date();
      b.setHours(bArray[0]);
      b.setMinutes(bArray[1]);
      var btimeStamp = b.getTime();
      return btimeStamp;
    }
    let endTime = function (endtime) {
      var eArray = endtime.split(":");
      if (eArray.length !== 2) {
        return false;
      }
      var e = new Date();
      e.setHours(eArray[0]);
      e.setMinutes(eArray[1]);
      var etimeStamp = e.getTime();
      return etimeStamp;
    }
    if (timeStamp > beginTime("00:00") && timeStamp < endTime("20:00")) {
      wx.navigateTo({
        url: '/pages/morning/morning',
      })
    } else {
      wx.navigateTo({
        url: '/pages/sleep/sleep',
      })
    }
  },
  //早睡早起
  tofinished: function (e) {
    var that = this;
    var jobsList = e.currentTarget.dataset.jobslist;
    var index = 5;
    if (jobsList[5].isEnd === 0) {
      that.morningAndSleep();
    } else if (jobsList[5].idEnd === 1) {
      that.getMoneyInterface(jobsList[5].id, index);
      that.getWelfareInfo();
    }
    else if (jobsList[5].isEnd === 2) {
      that.toastOut();
    }
  },
  // 跳转眼保健操界面
  turnKeepEye: function () {
    wx.navigateTo({
      url: '/pages/eyes/eyes',
    })
  },
  //眼保健操
  keepeyes: function (e) {
    var that = this;
    var jobsList = e.currentTarget.dataset.jobslist;
    var index = 6;
    if (jobsList[6].isEnd === 0) {
      wx.navigateTo({
        url: '/pages/eyes/eyes',
      })
    } else if (jobsList[6].isEnd === 1) {
      that.getMoneyInterface(jobsList[6].id, index);
      that.getWelfareInfo();
    }
    else if (jobsList[6].isEnd === 2) {
      that.toastOut();
    }
  },
  // 跳转喝水打卡
  turnDrink: function () {
    wx.navigateTo({
      url: '/pages/drink/drink',
    })
  },
  //喝水打卡
  drink: function (e) {
    var that = this;
    var jobsList = e.currentTarget.dataset.jobslist;
    var index = 7;
    if (jobsList[7].isEnd === 0) {
      wx.navigateTo({
        url: '/pages/drink/drink',
      })
    } else if (jobsList[7].isEnd === 1) {
      that.getMoneyInterface(jobsList[7].id, index);
      that.getWelfareInfo();
    } else if (jobsList[7].isEnd === 2) {
      that.toastOut();
    }
  },
  // 跳转吃饭打卡
  turnLunch: function () {
    var that = this;
    wx.navigateTo({
      url: '/pages/lunch/lunch',
    })
  },
  // 吃饭打卡
  keepmeal: function (e) {
    var that = this;
    var jobsList = e.currentTarget.dataset.jobslist;
    var index = 8;
    if (jobsList[8].isEnd === 0) {
      wx.navigateTo({
        url: '/pages/lunch/lunch',
      })
    } else if (jobsList[8].isEnd === 1) {
      that.getMoneyInterface(jobsList[8].id, index);
      that.getWelfareInfo();
    } else if (jobsList[8].isEnd === 2) {
      that.toastOut();
    }
  },
  // 显示领取元宝奖励的弹窗
  timeToast: function (a) {
    var that = this;
    var money = that.data.money;
    that.setData({
      timeShow: true,
      showMaskNext: true,
      money: money + a,
      timeyuanbao: a,
    })
    var userMoney = Math.floor((money + a) / 10000 * 100) / 100;
    that.setData({
      userMoney: userMoney,
    })
  },
  // 签到奖励弹窗
  signToast: function (a) {
    var that = this;
    var money = that.data.money;
    that.setData({
      showMask: true,
      fourShow: true,
      timeyuanbao: a,
    })
    var userMoney = Math.floor(money / 10000 * 100) / 100;
    that.setData({
      userMoney: userMoney,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var isReview = wx.getStorageSync("isReview");
    var isReview1 = wx.getStorageSync("isReview1");
    var userMoney = Math.floor(app.globalData.money / 10000 * 100) / 100;
    that.setData({
      money: app.globalData.money,
      userMoney: userMoney,
      gameShow: true,
      isReview1: isReview1,
      isReview: isReview,
    })
    that.getWelfareInfo();
    var count = 0;
    var insertScreenAdTimer = setInterval(function () {
      count ++;
      console.log(count);
      if(count > 2) {
        that.insertScreenAD();
        clearInterval(insertScreenAdTimer);
      }
    },1000)
    that.insertScreenAdTimer = insertScreenAdTimer;
  },
  // 获取福利页面信息
  getWelfareInfo: function () {
    var that = this;
    var userId = wx.getStorageSync("userId");
    //福利页面 接口7
    var data7 = {
      deviceProperties: app.globalData.deviceProperties,
      user: {
        userId: userId,
      }
    }
    data7 = JSON.stringify(data7);
    data7 = util.base64_encode(data7);
    data7 = util.xxtea_encrypt(data7, key);
    wx.request({
      url: resurl + '/interface/sdkData?requestId=7&a=1&b=2',
      data: data7,
      header: {
        "content-type": "application/json",
        "dataType": "json",
      },
      method: "post",
      success: function (res) {
        res = util.xxtea_decrypt(res.data, key);
        res = util.base64_decode(res);
        res = JSON.parse(res);
        // console.log(res);
        if (res.resultCode === 0) {
          res = JSON.parse(res.data);
          // console.log(res.isSign);
          if (res.isSign === 0) {
            // 如果未签到，则弹出签到奖励，并且调用签到接口
            that.sign();
          }
          console.log(res);
          console.log(res.jobsList[4])
          var jobsList = res.jobsList;
          var [...arrList] = [...that.data.arrList];
          // console.log(eventList)
          for (var i = 0; i < res.signDay % 7; i++) {
            // console.log(arrList[i].signedSrc);
            arrList[i].signingSrc = arrList[i].signedSrc;
            arrList[i].signingColor = arrList[i].signedColor;
          }
          that.setData({
            arrList: arrList,
            signDay: res.signDay % 7,
            isSign: res.isSign,
            jobsList: jobsList,
          })
          if (jobsList[0].isEnd === 0) {
            that.setData({
              showBtn: true,
            })
          }
        }
      }
    })
  },
  //用户签到
  sign: function () {
    var that = this;
    var money = that.data.money;
    var userId = wx.getStorageSync("userId");
    var data8 = {
      deviceProperties: app.globalData.deviceProperties,
      user: {
        userId: userId,
      }
    }
    data8 = JSON.stringify(data8);
    data8 = util.base64_encode(data8);
    data8 = util.xxtea_encrypt(data8, key);
    wx.request({
      url: resurl + '/interface/sdkData?requestId=8&a=1&b=2',
      data: data8,
      header: {
        "content-type": "application/json",
        "dataType": "json",
      },
      method: "post",
      success: function (res) {
        res = util.xxtea_decrypt(res.data, key);
        res = util.base64_decode(res);
        res = JSON.parse(res);
        console.log(res);
        if (res.resultCode === 0) {
          res = JSON.parse(res.data);
          console.log(res);
          var app = getApp();
          app.globalData.money = money + res.getMoney;
          that.setData({
            money: app.globalData.money,
          })
          that.signToast(res.getMoney);

          that.setData({
            signDay: res.signDay,
            isSign: res.isSign,

          })
        }

      }
    })
  },
  // 关闭弹窗
  clickclosefour: function () {
    this.setData({
      fourShow: false,
      showMask: false
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    clearInterval(that.insertScreenAdTimer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this;
    clearInterval(that.insertScreenAdTimer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
   
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})